package com.sike.netty.jinjie.channel.closefuture;


import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Scanner;

@Slf4j
public class CloseFutureClient_02 {
    public static void main(String[] args) throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(new NioEventLoopGroup());
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                // 打印调试日志
                ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                ch.pipeline().addLast(new StringEncoder());
            }
        });

        // 获取 Channel
        Channel channel = bootstrap.connect("127.0.0.1",8081).sync().channel();

        new Thread(() -> {
            System.out.println("请输入要发送的信息，exit 表示退出....");
            Scanner scanner = new Scanner(System.in);
            while (true) {
                String line = scanner.nextLine();
                if ("exit".equals(line)) {
                    channel.close();
                    break;
                }

                channel.writeAndFlush(line);
            }
        },"close-future").start();

        // 获取 CloseFuture
        ChannelFuture closeFuture = channel.closeFuture();
        log.info("等待 Channel 关闭...");
        // 同步等待 Channel 关闭
        closeFuture.sync();
        log.info("Channel 已关闭，执行善后工作...");
    }
}
